<?php

namespace App\Service\users;

use App\Jobs\WithdrawQueue;
use App\Models\users\UsersWithdrawLogModel;
use Illuminate\Support\Facades\Log;
use lxs\config\BaseStatic;
use lxs\tools\Tools;

class WithdrawService extends BaseStatic
{

    /**
     * 用户提现表单提交
     */
    public function userWithdrawSubmit($uid, $formData) {

        try {

            $withDraw = new UsersWithdrawLogModel();
            $withDraw->order_sn = Tools::uniqidDate('TX_');
            $withDraw->uid = $uid;
            $withDraw->type = $formData['change_type'];
            $withDraw->amount = $formData['amount'];
            $withDraw->commission = $formData['commission'];
            $withDraw->real_amount = $formData['withdraw_money'];
            $withDraw->status = UsersWithdrawLogModel::WITHDRAW_APPLYING;
            $withDraw->create_time = time();
            $withDraw->save();

            $userInfo = UsersService::instance()->getUserInfo($uid);
            if ($formData['withdraw_money'] > $userInfo->amount) {
                return self::serviceReturn(400, '提现金额不能大于账户余额');
            }

            if (isset($withDraw->id)) {
                $remark = '用户：' . $userInfo->nickname . ' 申请提现：' . $formData['withdraw_money'] . '元';
                WithdrawQueue::dispatch($uid, -$formData['withdraw_money'], 'withdraw', $remark, UsersWithdrawLogModel::WITHDRAW_APPLYING);
            }

            return self::serviceReturn(200, '提交成功', ['withdraw_id' => $withDraw->id]);
        } catch (\Throwable $e) {
            Log::error('用户提现表单提交异常：' . $e->getMessage() . $e->getLine());
            return self::serviceReturn(400, '用户提现表单提交执行失败');
        }

    }


}
